package com.rc.saas.tenant.controller.tenant;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.redis.RedisLoader;
import com.rc.saas.tenant.common.utils.DateHelper;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.rc.RcOperatorAccountRecord;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.rc.RcOperatorAccountRecordSearch;
import com.rc.saas.tenant.service.finance.RcOperatorAccountRecordService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.rc.ExportRcOperatorAccountRecordVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;


/**
 * @author zhongz
 * @data 20220719
 */
@Controller
@RequestMapping("/rcOperatorAccountRecord")
public class RcOperatorAccountRecordController extends TenantBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisLoader redisLoader;

    @Autowired
    private RcOperatorAccountRecordService rcOperatorAccountService;

    /**
     * 跳转资金交易流水明细页面
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String rcOperatorAccountRecordPage() {
        return "/templates/finance/rcOperatorAccountRecordList";
    }


    /**
     * 资金交易流水明细列表数据
     * @return
     */
    @RequestMapping(value = "/listRcOperatorAccountRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listRcOperatorAccountRecord(RcOperatorAccountRecordSearch rcOperatorAccountRecordSearch) {
        PageInfo<RcOperatorAccountRecord> pageInfo = rcOperatorAccountService.searchByCondition(rcOperatorAccountRecordSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 修改入账时间
     * @param operatorAccountRecordId
     * @param recordTime
     * @return
     */
    @RequestMapping(value = "/updateRcOperatorAccountRecordTime", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateRcOperatorAccountRecordTime(String operatorAccountRecordId, String recordTime) {
        if (StringUtils.isBlank(operatorAccountRecordId) || StringUtils.isBlank(recordTime)){
            return TResponse.FAIL("参数错误");
        }
        RcOperatorAccountRecord queryInfo = rcOperatorAccountService.selectByPrimaryKey(Long.parseLong(operatorAccountRecordId));
        if (queryInfo==null){
            return TResponse.FAIL("请求错误");
        }
        RcOperatorAccountRecord info = new RcOperatorAccountRecord();
        info.setOperatorAccountRecordId(queryInfo.getOperatorAccountRecordId());
        info.setRecordTime(DateHelper.stringToDate(recordTime, DateHelper.DATE_COMMON_FORMAT));
        info.setLastUpdatedTime(new Date());
        rcOperatorAccountService.updateTimeByPrimaryKey(info);
        return TResponse.SUCCESS();
    }

    /**
     * 跳转资金交易流水明细详情
     * @return
     */
    /*@RequestMapping(value = "/detailRcOperatorAccountRecordIndex",method = RequestMethod.GET)
    public String detailRcOperatorAccountRecordIndex(){
        return "/templates/finance/detailRcOperatorAccountRecord";
    }*/
    /**
     * 资金交易流水明细详情
     * @return
     */
    /*@RequestMapping(value = "/detailRcOperatorAccountRecord", method = RequestMethod.GET)
    @ResponseBody
    public RcOperatorAccountRecord detailRcOperatorAccountRecord(Long operatorAccountRecordId) {
        return rcOperatorAccountService.selectByPrimaryKey(operatorAccountRecordId);
    }*/

    /**
     * 资金交易流水明细详情
     * @return
     */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    public String edit(Model model, @PathVariable("id") Long operatorAccountRecordId) {
        RcOperatorAccountRecord info = rcOperatorAccountService.selectByPrimaryKey(operatorAccountRecordId);
        model.addAttribute("info", info);
        return "/templates/finance/detailRcOperatorAccountRecord";
    }

    /**
     * 导出订单列表
     */
    @ResponseBody
    @RequestMapping("/exportRcOperatorAccountRecord")
    public TResponse exportRcOperatorAccountRecord(RcOperatorAccountRecordSearch rcOperatorAccountRecordSearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=false; path=/");
        ExportUtils.setDefaultPaging(rcOperatorAccountRecordSearch);
        if (rcOperatorAccountRecordSearch.getCount() == 0 || rcOperatorAccountRecordSearch.getCount() == null) {
            rcOperatorAccountRecordSearch.setCount(rcOperatorAccountRecordSearch.getLimit());
        }

        if (rcOperatorAccountRecordSearch.getCount() > 200000) {
            return TResponse.FAIL("最多导出二十万数据");
        }
        if (rcOperatorAccountRecordSearch.getCount() >= 100000) {
            String exportData = (String) redisLoader.get("saas:exportData");
            if (exportData != null) {
                return TResponse.FAIL("导出人数过多,请稍后重试");
            }
            TenantUser user = ShiroUtils.getSessionUser();
            redisLoader.set("saas:exportData", user.getTenantCode(), 1000 * 20);
        }

        //导出拼接开始条数
        rcOperatorAccountRecordSearch.setOffset(rcOperatorAccountRecordSearch.getLimit() * (rcOperatorAccountRecordSearch.getOffset() - 1));
        List<ExportRcOperatorAccountRecordVo> list = rcOperatorAccountService.exportRcOperatorAccountRecord(rcOperatorAccountRecordSearch);
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("资金交易流水明细列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExportRcOperatorAccountRecordVo.class).sheet("资金交易流水明细列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出资金交易流水明细列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

}
